package logic

import (
	"context"

	"server-go/rpc/reward/internal/models"
	"server-go/rpc/reward/internal/svc"
	"server-go/rpc/reward/types/reward"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetContentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetContentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetContentLogic {
	return &GetContentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 数据页面 content
func (l *GetContentLogic) GetContent(in *reward.GetContentInput) (*reward.GetContentOutput, error) {
	out := &reward.GetContentOutput{}
	taskLs, total, err := (&models.TasksDao{Audit: 1}).GetContentLs(l.svcCtx.Db, int(in.PageNo), int(in.PageSize), in.TaskTypeId, in.SearchValue)
	if err != nil {
		return out, err
	}
	// 获取发布者姓名
	userIds := []int{}
	for _, v := range taskLs {
		userIds = append(userIds, v.Userid)
	}
	// map[user_id]nick_name
	userMap := make(map[int]*models.UsersDao)
	users, err := (&models.UsersDao{}).FindByIds(l.svcCtx.Db, userIds)
	if err != nil {
		return out, err
	}
	for _, user := range users {
		userMap[user.Id] = user
	}
	// 获取任务类型 map[id]name
	taskTypeMap := make(map[int]string)
	taskTypes, err := (&models.TaskTypeDao{}).Find(l.svcCtx.Db)
	if err != nil {
		return out, err
	}
	for _, v := range taskTypes {
		taskTypeMap[v.Id] = v.Typename
	}
	// 匹配最终数据
	for _, v := range taskLs {
		avatar, nickName, userIntro := "", "", ""
		if v1, ok := userMap[v.Userid]; ok {
			avatar = v1.Username
			nickName = v1.Nickname
			userIntro = v1.Userintro
		}
		description := ""
		if v1, ok := taskTypeMap[v.Typeid]; ok {
			description = v1
		}
		out.ContentData = append(out.ContentData, &reward.GetContent{
			Avatar:      avatar,
			Bounty:      uint32(v.Bounty),
			Content:     v.Taskintro,
			Description: description,
			Enddate:     v.Enddate,
			Id:          uint32(v.Id),
			Nickname:    nickName,
			Title:       v.Tasktitle,
			Userintro:   userIntro,
		})
	}
	out.Total = uint32(total)
	return out, nil
}
